package com.yonyougov.devops.cruxcisupport.thread;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yonyougov.devops.cruxcisupport.appversioninfo.vo.AppVersionInfoVo;
import com.yonyougov.devops.cruxcisupport.util.HttpUtils;
import com.yonyougov.devops.fwc.core.util.ServiceLocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.util.concurrent.Callable;

/**
 * 获取某个环境下某个应用的版本信息
 */
public class GetAppVersionCallable implements Callable<AppVersionInfoVo> {
    private Logger logger = LoggerFactory.getLogger(GetAppVersionCallable.class);
    private String requestUrl;
    private String appName;

    public GetAppVersionCallable(String requestUrl, String appName) {
        this.requestUrl = requestUrl;
        this.appName = appName;
    }

    @Override
    public AppVersionInfoVo call() {
        AppVersionInfoVo appVersionInfoVo = new AppVersionInfoVo();
        appVersionInfoVo.setAppName(this.appName);
        try {
            ResponseEntity<String> stringResponseEntity = HttpUtils.get(this.requestUrl, String.class);
            int statusCodeValue = stringResponseEntity.getStatusCodeValue();
            if (HttpStatus.OK.value() == statusCodeValue) {
                String body = stringResponseEntity.getBody();
                ObjectMapper objectMapper = ServiceLocator.getService(ObjectMapper.class);
                //JSONObject obj = JSONObject.parseObject(body);
                JsonNode node = objectMapper.readTree(body);
                String appVersion = node.get("Implementation-Version").asText();
                appVersionInfoVo.setAppVersion(appVersion);
            } else {
                appVersionInfoVo.setAppVersion("未知");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("catch exception is : {}", e.getMessage());
            appVersionInfoVo.setAppVersion("未知");
        }
        return appVersionInfoVo;
    }
}
